package com.hzgj.soa.spring;

import com.hzgj.bcl.soa.api.ProxyFactory;
import com.hzgj.bcl.soa.config.ReferenceDef;
import com.hzgj.bcl.soa.monitor.MonitorConfig;
import com.hzgj.bcl.soa.monitor.MonitorService;
import com.hzgj.bcl.soa.rpc.RpcDispatcher;
import com.hzgj.bcl.util.IocContext;
import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class MonitorBean implements ApplicationContextAware, InitializingBean, DisposableBean {

    @Getter
    @Setter
    private ReferenceDef referenceDef;
    @Setter
    private String id;
    private RpcDispatcher rpcDispatcher;
    private ApplicationContext applicationContext;

    @Override
    public void afterPropertiesSet() throws Exception {
        MonitorConfig.getInstance().setMonitorService(getObject());
    }

    @Override
    public void destroy() throws Exception {
        if (rpcDispatcher != null) {
            rpcDispatcher.stop();
        }
    }

    public <T> T getObject() {
        rpcDispatcher = applicationContext.getBean(RpcDispatcher.class);
        return (T) ProxyFactory.proxyBuilder(MonitorService.class).dispatch(rpcDispatcher).
                referenceDef(referenceDef).build();
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
        IocContext.applicationContext = applicationContext;
    }
}